package com.heer.imagepick;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;

/**
 * PhotoWall中GridView的适配器
 *
 * @author hanj
 */

public class PhotoWallSingleAdapter extends BaseAdapter {
    private Activity context;
    private ArrayList<String> imagePathList = null;

    private SDCardImageLoader loader;

    // 记录是否被选择
    private JSONObject obj;
    private String SD_CARD_TEMP_DIR;

    public String getSD_CARD_TEMP_DIR() {
        return SD_CARD_TEMP_DIR;
    }

    public void setSD_CARD_TEMP_DIR(String sD_CARD_TEMP_DIR) {
        SD_CARD_TEMP_DIR = sD_CARD_TEMP_DIR;
    }

    public PhotoWallSingleAdapter(Activity context, ArrayList<String> imagePathList) {
        this.context = context;
        this.imagePathList = imagePathList;

        loader = new SDCardImageLoader(DensityUtils.getScreenW(context),
                DensityUtils.getScreenH(context));
        obj = new JSONObject();
        SD_CARD_TEMP_DIR = Environment.getExternalStorageDirectory()
                + File.separator + "tmpPhoto.jpg";
    }

    @Override
    public int getCount() {
        return imagePathList == null ? 0 : imagePathList.size();
    }

    @Override
    public Object getItem(int position) {
        return imagePathList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        final ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(
                    R.layout.photo_wall_item, null);
            holder = new ViewHolder();

            holder.imageView = (ImageView) convertView
                    .findViewById(R.id.photo_wall_item_photo);
            holder.checkBox = (CheckBox) convertView
                    .findViewById(R.id.photo_wall_item_cb);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        String filePath = (String) getItem(position);
        if (filePath.equals("index")) {
            holder.imageView.setImageResource(R.drawable.icon41);
            holder.checkBox.setVisibility(View.GONE);
            holder.imageView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    String state = Environment.getExternalStorageState();
                    if (state.equals(Environment.MEDIA_MOUNTED)) {
                        Intent takePictureFromCameraIntent = new Intent(
                                MediaStore.ACTION_IMAGE_CAPTURE);
                        takePictureFromCameraIntent.putExtra(
                                MediaStore.EXTRA_OUTPUT,
                                Uri.fromFile(new File(SD_CARD_TEMP_DIR)));
                        context.startActivityForResult(
                                takePictureFromCameraIntent, 2);
                    } else {
                        Toast.makeText(context,
                                context.getString(R.string.sdcard_empty),
                                Toast.LENGTH_LONG).show();
                    }
                }
            });
        } else {
            try {
                // tag的key必须使用id的方式定义以保证唯一，否则会出现IllegalArgumentException.
                holder.imageView.setTag(R.id.tag_first, position);
                holder.checkBox.setVisibility(View.VISIBLE);
                holder.checkBox.setTag(R.id.tag_first, position);
                holder.checkBox.setTag(R.id.tag_second, holder.imageView);
                holder.imageView.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        try {
                            Integer position = (Integer) v
                                    .getTag(R.id.tag_first);
                            if (obj.has("select"))
                                if (String.valueOf(position)
                                        .equals(String.valueOf(obj
                                                .getString("select")))) {
                                    holder.checkBox.setChecked(false);
                                } else {
                                    holder.checkBox.setChecked(true);
                                }
                            else
                                holder.checkBox.setChecked(true);
                            notifyDataSetChanged();
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                });
                holder.checkBox
                        .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                            @Override
                            public void onCheckedChanged(
                                    CompoundButton buttonView, boolean isChecked) {

                                try {
                                    Integer position = (Integer) buttonView
                                            .getTag(R.id.tag_first);

                                    ImageView image = (ImageView) buttonView
                                            .getTag(R.id.tag_second);
                                    if (isChecked) {
                                        obj.put("select",
                                                String.valueOf(position));

                                        image.setColorFilter(context
                                                .getResources()
                                                .getColor(
                                                        R.color.image_checked_bg));
                                    } else {
                                        // obj.put("select",
                                        // String.valueOf(-1));
                                        image.setColorFilter(null);
                                    }
                                } catch (JSONException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                        });
                if (obj.has("select"))
                    if (obj != null && !obj.getString("select").equals("-1"))
                        if (String.valueOf(position).equals(
                                String.valueOf(obj.getString("select"))))
                            holder.checkBox.setChecked(true);
                        else
                            holder.checkBox.setChecked(false);
                holder.imageView.setTag(filePath);
                loader.loadImage(4, filePath, holder.imageView);

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return convertView;
    }

    private class ViewHolder {
        ImageView imageView;
        CheckBox checkBox;
    }

    public JSONObject getObj() {
        return obj;
    }

    public void setObj(JSONObject obj) {
        this.obj = obj;
    }
}
